module Lex
( lex1,lexAMAP
) where
import qualified My
import MyData.Form
import Data.Char(isSpace)
import Data.Tuple(swap)

type Lexed s = (F s,[s])

clean = dropWhile ((==')') . head)

genlex :: ([S] -> Lexed S) -> S -> Lexed S
genlex lex = fmap clean . lex . clean . lexParen

lex1 :: S -> Lexed S
lex1 = genlex llex1
lexAMAP = genlex llexAMAP

llex1 :: [S] -> Lexed S
llex1 [] = (nil,[])
llex1 ((')':_):ss) = (nil,ss)
llex1 (('(':_):ss) = llexAMAP ss
llex1 (s:ss) = (A s,ss)

llexAMAP :: [S] -> Lexed S
llexAMAP [] = (nil,[])
llexAMAP ((')':_):ss) = (nil,ss)
llexAMAP (('(':_):ss) = let (l,lrest)=llexAMAP ss;(f,rest)=llexAMAP lrest in (C l f,rest)
llexAMAP (s:ss) = let (f,rest)=llexAMAP ss in (C (A s) f,rest)

lexUOC :: (a -> Bool) -> [a] -> [[a]]
lexUOC isUOC = My.groupAnd $ not . isUOC
slexUOC isUOC = lexUOC $ My.orF [isSpace,isUOC]
cslexUOC cs = slexUOC (`elem` cs)
lexParen :: S -> [S]
lexParen = filter (not . isSpace . head) . cslexUOC "()"

test :: (S -> Lexed S) -> S -> ([S], S)
test lex = fmap pr . swap . lex
